package com.moonshine.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.adobe.ac.pmd.parser.IParserNode;
import com.adobe.ac.pmd.parser.NodeKind;

public class NodeUtils {

	public static Map<String, String> getParamaterList(IParserNode node) {
		Map<String, String> map = new HashMap<String, String>();
		if (node.is(NodeKind.FUNCTION)) {
			// find the list from the function node
			IParserNode list = recursiveFindNode(node, NodeKind.PARAMETER_LIST);
			IParserNode param;

			if (list.numChildren() != 0) {
				for (IParserNode p : list.getChildren()) {
					// find the block containing the actual var name and type
					param = recursiveFindNode(p, NodeKind.NAME_TYPE_INIT);
					if (param != null && param.getChildren().size() >= 2) {
						map.put(param.getChild(0).getStringValue(), param
								.getChild(1).getStringValue());
					}
				}
			}
		}
		return map;
	}

	public static void recursiveFindNodes(IParserNode node, NodeKind kind,
			List<IParserNode> list) {
		if (node.is(kind))
			list.add(node);
		IParserNode found = null;
		if (node.numChildren() != 0) {
			for (IParserNode child : node.getChildren()) {
				if (child.is(kind)) {
					list.add(child);
				} else if (child.numChildren() != 0) {
					recursiveFindNodes(child, kind, list);

				}

			}
		}

	}

	private static final List<IParserNode> cachedList = new ArrayList<IParserNode>();

	public static IParserNode recursiveFindNode(IParserNode node, NodeKind kind) {
		if (node.is(kind))
			return node;
		IParserNode found = null;
		if (node.numChildren() != 0) {
			for (IParserNode child : node.getChildren()) {
				if (child.is(kind)) {
					found = child;
				} else if (child.numChildren() != 0) {
					found = recursiveFindNode(child, kind);

				}
				if (found != null && found.is(kind)) {
					return found;
				} else {
					found = null;
				}
			}
		}
		return null;

	}
}
